<!-- axios采用get获取json数据，通过滤器只保留CN相关的城市信息，通过id来查找城市信息 -->
<template>
  <div class="CityJson">
    <div class="city-list">
      <el-button @click="getCityInfo">获取城市列表</el-button>
      <el-input v-model="searchId" type="number" placeholder="输入城市ID" />
      <el-button @click="findCityById">查找城市</el-button>
    </div>
    <div v-if="foundCity">
      <h2>找到的城市信息</h2>
      <p>ID: {{ foundCity.id }}</p>
      <p>Name: {{ foundCity.name }}</p>
      <p>Country: {{ foundCity.country }}</p>
      <p>Coordinates: {{ foundCity.coord.lat }}, {{ foundCity.coord.lon }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "CityJson",
  data () {
    return {
      cityList: [], // 存储城市列表
      filteredCityList: [], // 存储过滤后的城市列表
      searchId: '', // 存储用户输入的ID
      foundCity: null // 存储找到的城市信息
    };
  },
  methods: {
    getCityInfo () {
      axios.get("/resources/json/city.list.json")
        .then((res) => {
          this.cityList = res.data; // 将获取到的城市列表存储在 data 中
          this.filteredCityList = this.cityList.filter(city => city.country === 'CN'); // 过滤出国家为中国的城市
          console.log(this.filteredCityList);
        })
        .catch((error) => {
          console.error('请求出错:', error);
        });
    },
    findCityById () {
      const id = parseInt(this.searchId, 10); // 将输入的字符串转换为整数
      if (isNaN(id)) {
        alert('请输入有效的城市ID！');
        return;
      }
      this.foundCity = this.filteredCityList.find(city => city.id === id); // 查找匹配的 city
      if (!this.foundCity) {
        alert('未找到对应的城市信息！');
      }
    }
  }
};
</script>

<style scoped>
</style>